I'm creating a new user and checking whether the user email previously exists or not. If not then it is creating a new user and saving it. What do I need to correct this validation error I am getting?
I have already tried by setting name as not required. But it still does not work.
This is my User model.
User.js
import mongoose from 'mongoose'
const UserSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
unique: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
profilePic: {
type: String,
default: "",
},
},
{ timestamps: true }
);
const User = mongoose.model("User",UserSchema)
export default User
this is my router file
import User from '../model/User.js'
import express from 'express'
const router = express.Router()
//register
router.post("/register",async (req,res) => {
try{
const newUser = new User({
username:req.body.username,
password:req.body.password,
email:req.body.email
})
const user =await newUser.save()
res.status(200).json(user)
}catch(err){
res.status(500).json(err)
}
})
export default router
this is my app.js
import express from 'express'
import mongoose from 'mongoose'
import dotenv from 'dotenv'
import UserRoute from './routes/User.js'
const app = express()
dotenv.config()
app.use(express.json())
app.use(express.urlencoded({ extended: true }));
const PORT = process.env.PORT || 3000
mongoose
.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(console.log("Connected to MongoDB"))
.catch((err) => console.log(err));
app.use("/api/auth",UserRoute)
app.listen(PORT , () => console.log(`backend started on ${PORT}` ))
i also just notice one thing if i tries to bcrypt the password and then use it in my route then after making request in postman instead of error message i am getting null object {} in postman what's the reason ???
what is the issue on the code i tried different ways to fix this by taking reference from stack overflow but didn't work
thanks for your help
How is your request body look like? Are you sure there are req.body.username and req.body.passwords? Try console.log them before you save the user and check they are not undefined.